package de.slothsoft.wasbinich.swingclient.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;

import de.slothsoft.commons.res.CommonImages;
import de.slothsoft.wasbinich.swingclient.io.Dialogs;
import de.slothsoft.wasbinich.swingclient.io.ImageUtil;
import de.slothsoft.wasbinich.swingclient.res.Images;

public class ImageControl extends JLabel {

    private static final long serialVersionUID = -6648922795144232453L;
    private static final Logger LOGGER = Logger.getGlobal();

    private final JButton button;
    private String imageData;
    private Icon icon;

    public ImageControl() {
	setBorder(new EmptyBorder(1, 1, 1, 1));
	this.button = createButton();
	add(this.button);
    }

    private JButton createButton() {
	JButton result = new JButton();
	ImageIcon icon = CommonImages.get(CommonImages.TOOLBAR_OPEN);
	result.setIcon(icon);
	result.setSize(icon.getIconWidth(), icon.getIconHeight());
	result.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent e) {
		performSelectFile();
	    }
	});
	return result;
    }

    protected void performSelectFile() {
	File file = Dialogs.selectImageFile(this);
	if (file != null) {
	    try {
		setImageData(ImageUtil.convertFileToString(file));
	    } catch (IOException e) {
		LOGGER.severe(e.getMessage());
	    }
	}
    }

    public String getImageData() {
	return this.imageData;
    }

    public void setImageData(String pictureData) throws IOException {
	this.imageData = pictureData;
	if (pictureData != null && !pictureData.isEmpty()) {
	    this.icon = Images.getPictureFromData(pictureData, getPreferredSize());
	    setIcon(this.icon);
	    setSize(this.icon.getIconWidth(), this.icon.getIconHeight());
	} else {
	    setIcon(null);
	}
    }

}
